package com.podcstr.service;

import com.podcstr.dao.CategoryDao;
import com.podcstr.entity.Category;
import com.podcstr.service.exception.ServiceException;
import org.apache.log4j.Logger;

import javax.ejb.Local;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author azim
 * @since 5/19/13 
 */

@Stateless
@Local(CategoryService.class)
public class CategoryServiceImpl implements CategoryService {

    private final Logger log = Logger.getLogger(CategoryServiceImpl.class.getName());

    @Inject
    private CategoryDao categoryDao;

    @Override
    public void add(Category category) throws ServiceException {

        Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
        Set violations = validator.validate(category);
        if (violations.size() > 0) {

            log.error(violations);
            throw new ServiceException(violations);
        }

        Category existingCategory = categoryDao.findCategoryByName(category.getName());
        if (existingCategory != null) {

            throw new ServiceException("Duplicate Category. This category already exists.");
        }

        categoryDao.add(category);

        log.info(new Date() + " : Added a new category with name : " + category.getName());
    }

    @Override
    public void delete(long categoryId) {

        categoryDao.delete(categoryId);
        log.info(new Date() + " : Deleting a category with id : " + categoryId + ".");
    }

    @Override
    public void update(Category category) {

        categoryDao.update(category);
        log.info(new Date() + " : Updated the category with id : " + category.getId() + ".");
    }

    @Override
    public List<Category> findAll() {

        log.info(new Date() + " : Returning the list of categories.");
        return categoryDao.findAll();
    }

    @Override
    public Category findCategoryById(long categoryId) {

        Category category = categoryDao.findById(categoryId);
        if (category != null) {
            log.info(new Date() + " : Returning a category with id : " + categoryId + ".");
        }

        return category;
    }

    @Override
    public List<Category> findParentCategories() {

        log.info(new Date() + " : Returning list of parent categories.");
        return categoryDao.fingParentCategories();
    }

    @Override
    public List<Category> findChildCategories(long parentId) {

        log.info(new Date() + " : Returning list of child categories with paen id : " + parentId + ".");
        return categoryDao.fingChildCategories(parentId);
    }
}
